package class06;

import java.util.Arrays;
import java.util.Comparator;

/**
 * @Auther: xw
 * @Create: 2022/3/21 14:52
 * @Description:自定义比较器
 */
public class DefineComparator {

    public static class Student {
        private Integer id;
        private String name;
        private Integer age;
        public Student() {
        }

        public Student(Integer id, String name, Integer age) {
            this.id = id;
            this.name = name;
            this.age = age;
        }

        @Override
        public String toString() {
            return "Student{" + "id=" + id +  ", name='" + name + '\'' +", age=" + age + '}';
        }
    }

    public static void printArray(int[] arrays){
        if(null == arrays || arrays.length <= 0){
            return;
        }
        for (int i = 0; i < arrays.length; i++) {
            System.out.print(arrays[i] + " ");
        }
        System.out.println();
        System.out.println("-----------------------------------------");
    }

    public static void printStudent(Student[] students){
        if(null == students || students.length <=0){
            return;
        }
        for (int i = 0; i < students.length; i++) {
            System.out.println(students[i]);
        }
        System.out.println("-----------------------------------------");
    }

    public static class compareStudentById implements Comparator<Student> {
        /**
         *  如果返回负数，认为第一个数应该排在前面
         *  如果返回正数，则认为第二个数应该排在前面
         *  如果返回零，则认为谁排前面无所谓
         * @param o1
         * @param o2
         * @return
         */
        @Override
        public int compare(Student o1, Student o2) {
            if(o1.id < o2.id){
                return -1;
            }else if(o1.id > o2.id){
                return 1;
            }else{
                return 0;
            }
        }
    }
    public static void main(String[] args) {
        int[] array = {9,5,7,12,0,1,5,4,89,12,52,12,1,23,7,0};
        printArray(array);
        Arrays.sort(array);
        printArray(array);

        Student s1 = new Student(2,"张三",22);
        Student s2 = new Student(1,"李四",29);
        Student s3 = new Student(5,"王五",12);
        Student s4 = new Student(3,"赵六",44);
        Student s5 = new Student(4,"孙七",25);

        Student[] students = {s1,s2,s3,s4,s5};
        printStudent(students);
        Arrays.sort(students,new compareStudentById());
        printStudent(students);
    }
}
